<template>
  <div class="table">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-friendadd"></i>管理账号
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="user_name" label="登录名" align="center"></el-table-column>
        <el-table-column prop="name" label="真实姓名" align="center"></el-table-column>
        <el-table-column prop="role" label="角色" align="center"></el-table-column>
        <el-table-column prop="phone" label="联系方式" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center"></el-table-column>
        <el-table-column label="添加时间" align="center">
          <template slot-scope="scope">{{ scope.row.date }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination_div">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="Totals"
          :page-size="10"
          :page-count="pageTotal"
          :current-page.sync="currPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog title="账号修改" :visible.sync="editVisible" width="40%" @close="cancledialog('form')">
      <el-form ref="form" :model="form" label-width="80px" label-position="left" :rules="rules">
        <el-form-item label="登录名" prop="user_name">
          <el-input v-model.trim="form.user_name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" placeholder="可以不填写，密码还是原来的"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="0"></el-option>
            <el-option label="普通管理员" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model.trim="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="form.status" label="1">启用</el-radio>
          <el-radio v-model="form.status" label="2">禁用</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancledialog('form')">取 消</el-button>
          <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "../../http/api.js";
export default {
  data() {
    var usernameyz = (rule, value, callback) => {
      const regall = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
      if (!value) {
        return callback(new Error("登陆名不能为空"));
      }
      if (regall.test(value)) {
        callback(new Error("登陆名不允许特殊字符"));
      } else {
        callback();
      }
    };
    var truenameGz = (rule, value, callback) => {
      var name_reg = /^[\u4e00-\u9fa5]{2,4}$/;
      if (!value) {
        return callback(new Error("真实姓名不能为空"));
      } else {
        if (!name_reg.test(value)) {
          callback(new Error("请输入正确的姓名"));
        } else {
          callback();
        }
      }
    };
    var phoneGZ = (rule, value, callback) => {
      const regphone = /^1\s*[34578]\s*(\d\s*){9}$/;
      if (!value) {
        return callback(new Error("联系方式不能为空"));
      }
      if (!regphone.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      //表格数据
      tableData: [],     
      editVisible: false, //编辑框里面默认看不见
      form: {
        //编辑弹出框中数据
        // user_name: "",
        // password: "",
        // name: "",
        // role: "",
        // phone: "",
        // status: ""
      },
      rules: {
        //编辑里表格中的判断规则
        user_name: [{ required: true, validator: usernameyz, trigger: "blur" }],
        name: [{ required: true, validator: truenameGz, trigger: "blur" }],
        role: [{ required: true, message: "请选择角色", trigger: "focus" }],
        phone: [{ required: true, validator: phoneGZ, trigger: "blur" }]
      },
      delVisible: false, //点击删除弹出的信息框状态默认为不显示
      currPage: 1, //分页页码
      Totals: 1, //总条数
      pageTotal: 2,
      roleToken: sessionStorage.getItem("Token"), //这个token是登陆时候成功返回的一个值，
      RoleAdmin_id: "", //获取当前修改这个账号的账号id
      DelateAdmin_id: "" //删除时候用到！ 这个账号的id
    };
  },
  methods: {
    getData() {
      //获取数据 1.列表接口：
      this.$post(api.admin_list, {
        token: this.roleToken,
        page: this.currPage
      })
        .then(res => {
          if (res.status == 0) {
            //应为接口给的和我写的名称不一致，变成一致下面：
            this.tableData = res.data.map((val, index, arr) => {
              let jsons = [];
              jsons.user_name = val.user_name; //登陆名
              jsons.name = val.real_name; //真是姓名
              jsons.role = val.authority; //角色 0 代表超级用户 1代表普通用户
              jsons.phone = val.phone; //联系方式
              jsons.status = val.status; //状态 1表示启用
              jsons.date = val.add_time; //创建时间
              jsons.admin_id = val.admin_id; //管理员id
              return jsons;
            });
            // 改变一下 数字表示什么意思
            this.tableData.forEach(val => {
              if (val.role == 0) {
                val.role = "超级管理员";
              }
              if (val.role == 1) {
                val.role = "普通管理员";
              }
              if (val.status == "1") {
                val.status = "启用";
              }
              if (val.status == "2") {
                val.status = "禁用";
              }
            });
            // 获取总条数和总页数
            this.Totals = res.total;
            this.pageTotal = res.pageTotal;
            this.currPage = res.currPage;
          } else {
            this.$message.error(res.msg);
          }
          // 如果登录过期
          if (res.status == "relogin") {
            this.$message.error(res.msg);
            this.$router.push("/login");
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    handleEdit(index, row) {
      //点击编辑      
      this.RoleAdmin_id = this.tableData[index].admin_id;
      // 2.为了获得账号详情接口：
      this.$post(api.admin_linfo, {
        token: this.roleToken,
        admin_id: this.tableData[index].admin_id
      }).then(res => {
        if (res.status == 0) {
          //应为接口给的和我写的名称不一致，变成一致下面：
          this.form = {
            user_name: res.data.user_name,
            password: "",
            name: res.data.real_name,
            role: res.data.authority,
            phone: res.data.phone,
            status: res.data.status
          };
        }
      });
      this.editVisible = true;
    },
    cancledialog(formRule) {
      //dialog关闭后清除验证条件
      this.$refs[formRule].resetFields();
      this.editVisible = false;
    },
    // 保存编辑
    saveEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.role == "超级管理员") {
            this.form.role = "0";
          }
          if (this.form.role == "普通管理员") {
            this.form.role = "1";
          }
          // 3.编辑接口！！：
          this.$post(api.admin_edit, {
            token: this.roleToken, //用户名token
            admin_id: this.RoleAdmin_id, //管理员id
            user_name: this.form.user_name,
            password: this.form.password,
            authority: this.form.role, //角色 0超级管理员 1：普通管理员
            real_name: this.form.name, //真实姓名
            phone: this.form.phone, //手机号
            status: this.form.status //用户状态 1 启用 2禁用
          })
            .then(res => {
              // 返回状态 relogin：登录过期 0：成功 1：不支持的请求方式 2：参数错误 3：操作失败，当前账号不存在 4：当前账号名已存在 5：初始超级管理员账号不可禁用 6：初始超级管理员账号不可修改权限 7：操作失败
              if (res.status == "relogin") {
                this.$message.error(res.msg);
                this.$router.push("/login");
              }
              if (res.status == "0") {
                this.$message.success(res.msg);
                this.getData();
              } else {
                this.$message.error(res.msg);
                this.getData();
              }
            })
            .catch(error => {
              this.$message.error(error);
            });         
          this.editVisible = false;
        } else {
          this.$message.error(`保存失败，请检查数据填写是否正确！`);
          return false;
        }
      });
    },

    handleDelete(index, row) {
      //删除按钮     
      this.delVisible = true;
      this.DelateAdmin_id = this.tableData[index].admin_id;
    },
    // 确定删除
    deleteRow() {
      this.$post(api.admin_delete, {
        token: this.roleToken,
        admin_id: this.DelateAdmin_id
      }).then(res => {
        // 返回状态 relogin：登录过期
        //  0：成功 1：不支持的请求方式 2：参数错误 3：操作失败，当前账号不存在 4：初始超级管理员账号不可删除！ 5：操作失败
        if (res.status == "relogin") {
          this.$message.error(res.msg);
          this.$router.push("/login");
        }
        if (res.status == "0") {
          this.$message.success(res.msg);
          this.getData();
        } else {
          this.$message.error(res.msg);
          this.getData();
        }
      });
      this.getData();
      this.delVisible = false;
    },
    //点击分页
    handleCurrentChange(val) {
      this.currPage = val;
      this.getData();
    }
  },
  created() {
    this.getData();
  }
};
</script>
<style scoped>
.pagination_div {
  margin-top: 20px;
  text-align: right;
}
</style>
